﻿
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using GameStateManagement.Screens.Base;
#endregion

namespace GameStateManagement.Mine
{
    /// <summary>
    /// A popup message box screen, used to display "are you sure?"
    /// confirmation messages.
    /// </summary>
    public class MyMessageBox : ButtonScreen
    {
        #region Fields

        string message;
        Texture2D gradientTexture;
        Rectangle okPosition;
        MyButton OKButton;
        MyButton CancelButton;
        
        const int BUTTON_SIZE = 48;
        #endregion

        #region Events

        public event EventHandler<MyEventArgs> Accepted;
        public event EventHandler<MyEventArgs> Cancelled;
        private float Scale = 0.6f;
        private int selectedEntry;

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor automatically includes the standard "A=ok, B=cancel"
        /// usage text prompt.
        /// </summary>
        public MyMessageBox(string message)
            : this(message, true)
        { }


        /// <summary>
        /// Constructor lets the caller specify whether to include the standard
        /// "A=ok, B=cancel" usage text prompt.
        /// </summary>
        public MyMessageBox(string message, bool includeUsageText) : base(message)
        {
            const string usageText = "\nA button, Space, Enter = ok" +
                                     "\nB button, Esc = cancel";
            //MyButton m = new MyButton("aa") { TextureName = "ok", Position = new Vector2() };
            if (includeUsageText)
                this.message = message + usageText;
            else
                this.message = message;

            IsPopup = true;

            TransitionOnTime = TimeSpan.FromSeconds(0.2);
            TransitionOffTime = TimeSpan.FromSeconds(0.2);
        }

        protected override void UpdateMenuEntryLocations()
        {
            //base.UpdateMenuEntryLocations();
        }

        /// <summary>
        /// Loads graphics content for this screen. This uses the shared ContentManager
        /// provided by the Game class, so the content will remain loaded forever.
        /// Whenever a subsequent MyMessageBox tries to load this same content,
        /// it will just get back another reference to the already loaded data.
        /// </summary>
        public override void LoadContent()
        {
            SpriteFont font = ScreenManager.Font;

            // Center the message text in the viewport.
            Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);
            Vector2 textSize = font.MeasureString(message);
            Vector2 textPosition = (viewportSize - textSize) / 2;

            // The background includes a border somewhat larger than the text itself.
            const int hPad = 32;
            const int vPad = 48;

            Rectangle backgroundRectangle = new Rectangle((int)textPosition.X - hPad,
                                                          (int)textPosition.Y - vPad,
                                                          (int)textSize.X + hPad * 2,
                                                          (int)textSize.Y + vPad * 2);



            okPosition.X = backgroundRectangle.X + backgroundRectangle.Width / 2 - okPosition.Width;
            okPosition.Y = backgroundRectangle.Y + backgroundRectangle.Height - okPosition.Height / 2 - 35;

            ContentManager content = ScreenManager.Game.Content;
            OKButton = new MyButton("OK") {
                TransitionEnabled = false,
                TextureName = "ok",
                Position = new Vector2(okPosition.X, okPosition.Y)
            };
            CancelButton = new MyButton("Cancel")
            {
                TransitionEnabled = false,
                TextureName = "cancel",
                Position = new Vector2(backgroundRectangle.X + backgroundRectangle.Width / 2, okPosition.Y) 
            };

            OKButton.Selected += (a, b) => Accepted(a, b);
            CancelButton.Selected += (a, b) => OnCancel(PlayerIndex.One);

            this.Buttons.Add(CancelButton);
            this.Buttons.Add(OKButton);

            foreach (var item in this.Buttons)
            {
                item.Load(this);
            }

            gradientTexture = content.Load<Texture2D>("gradient");
        }

        
        #endregion

        #region Handle Input


        /// <summary>
        /// Responds to user input, accepting or cancelling the message box.
        /// </summary>
        public override void HandleInput(InputState input)
        {
            PlayerIndex playerIndex;

            //// We pass in our ControllingPlayer, which may either be null (to
            //// accept input from any player) or a specific index. If we pass a null
            //// controlling player, the InputState helper returns to us which player
            //// actually provided the input. We pass that through to our Accepted and
            //// Cancelled events, so they can tell which player triggered them.
            //if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            //{
            //    // Raise the accepted event, then exit the message box.
            //    if (Accepted != null)
            //        Accepted(this, new MyEventArgs(playerIndex));

            //    ExitScreen();
            //}
            //else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            //{
            //    // Raise the cancelled event, then exit the message box.
            //    if (Cancelled != null)
            //        Cancelled(this, new MyEventArgs(playerIndex));

            //    ExitScreen();
            //}

            

            if (input.IsMenuLeft(ControllingPlayer))
            {
                selectedEntry--;
                if (selectedEntry < 0)
                    selectedEntry = Buttons.Count - 1;
                OnReady(selectedEntry);
            }

            // Move to the next menu entry?
            if (input.IsMenuRight(ControllingPlayer))
            {
                selectedEntry++;
                if (selectedEntry >= Buttons.Count)
                    selectedEntry = 0;
                OnReady(selectedEntry);
            }

      

            if (input.IsMenuSelect(ControllingPlayer, out playerIndex))
            {
                OnSelectEntry(selectedEntry, playerIndex);
            }
            else if (input.IsMenuCancel(ControllingPlayer, out playerIndex))
            {
                OnCancel(playerIndex);
            }
        }


        #endregion

        #region Draw


        /// <summary>
        /// Draws the message box.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            SpriteFont font = ScreenManager.Font;

            // Darken down any other screens that were drawn beneath the popup.
            ScreenManager.FadeBackBufferToBlack(TransitionAlpha * 2 / 3);

            // Center the message text in the viewport.
            Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            Vector2 viewportSize = new Vector2(viewport.Width, viewport.Height);
            Vector2 textSize = font.MeasureString(message);
            Vector2 textPosition = (viewportSize - textSize) / 2;

            // The background includes a border somewhat larger than the text itself.
            const int hPad = 32;
            const int vPad = 64;

            Rectangle backgroundRectangle = new Rectangle((int)textPosition.X - hPad,
                                                          (int)textPosition.Y - vPad,
                                                          (int)textSize.X + hPad * 2,
                                                          (int)textSize.Y + vPad * 2);

            // Fade the popup alpha during transitions.
            Color color = Color.White * TransitionAlpha;

            spriteBatch.Begin();


            // Draw the background rectangle.
            spriteBatch.Draw(gradientTexture, backgroundRectangle, color);

            // Draw the message box text.
            spriteBatch.DrawString(font, message, textPosition, color);

            //okPosition.X = backgroundRectangle.X + backgroundRectangle.Width / 2 - okPosition.Width;
            //okPosition.Y = backgroundRectangle.Y + backgroundRectangle.Height - okPosition.Height / 2 - 10;

            OKButton.Position = new Vector2(backgroundRectangle.X + backgroundRectangle.Width / 2 - okPosition.Width + 15,
                backgroundRectangle.Y + backgroundRectangle.Height - okPosition.Height / 2 - 40);

            CancelButton.Position = new Vector2(backgroundRectangle.X + backgroundRectangle.Width / 2 - CancelButton.Texture.Width - 15,
                backgroundRectangle.Y + backgroundRectangle.Height - okPosition.Height / 2 - 40);

            // Draw Buttons
            //spriteBatch.Draw(okTexture, new Vector2(okPosition.X, okPosition.Y),
            //    new Rectangle(0, 0, okTexture.Width, okTexture.Height / 2 - 2), Color.White,
            //    0f, Vector2.Zero, Scale, SpriteEffects.None, 0f);

            //spriteBatch.Draw(cancelTexture,
            //    new Vector2(backgroundRectangle.X + backgroundRectangle.Width / 2, okPosition.Y),
            //    cancelSourceRect, Color.White,
            //    0f, Vector2.Zero, Scale, SpriteEffects.None, 0f);

            if (!IsExiting)
                for (int i = 0; i < Buttons.Count; i++)
                {
                    MyButton menuEntry = (MyButton)Buttons[i];

                    bool isSelected = IsActive && (i == selectedEntry);

                    //spriteBatch.DrawString(font, "Selected: " + isSelected.ToString(),
                    //    new Vector2(textPosition.X, textPosition.Y + (i + 1) * 30), color);
                    menuEntry.Draw(this, isSelected, gameTime);
                }
          
            spriteBatch.End();
            
        }


        public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
        {
            if (!IsExiting)
                for (int i = 0; i < Buttons.Count; i++)
                {
                    bool isSelected = IsActive && (i == selectedEntry);

                    Buttons[i].Update(this, isSelected, gameTime);
                }
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
        }

        

        #endregion
    }
}
